import { connection } from '../app/database/mysql';
import { oilModel } from './oil.model';

/**
 * 获取内容
 */
export const getOil = async (pageSize: number, pageNo: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS * FROM oil
  `;

  statement += ` ORDER by id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize

  // 执行查询
  const [data] = await connection.promise().query(statement);

  let totalStatement = `SELECT FOUND_ROWS() as total`
  const [result] = await connection.promise().query(totalStatement)
  let totalCount = result[0].total
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize

  let res = {
    data,
    totalPage,
    totalCount
  }
  // 提供数据
  return res;
}

/**
 * 按 ID 获取内容
 */
export const getIdOil = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM oil
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data[0];
}

/**
 * 创建内容
 */
export const createOil = async (post: oilModel) => {
  // 准备数据
  const statement = `
    INSERT INTO oil
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateOil = async (post: oilModel, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE oil
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const delteOil = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM oil
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}
